package edu.uob;

import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Table {
    private String tableName;
    private static List<String> columnNames;
    private static List<Row> rows;

    public Table() {
        // Constructor
    }

    // Getters and setters
    public static String insertRow(String tableName, String values) {
        values = values.replaceAll("'", "");

        // 将预处理后的值字符串转换为对象列表
        List<Object> valueList = Arrays.asList(values.split(","));

        // 去除首尾空格
        valueList.replaceAll(s -> ((String) s).trim());
        System.out.println("Preprocessed value list: " + valueList);

        String filePath = "." + File.separator + "databases" + File.separator + CmdType.getDbName() + File.separator + tableName + ".tab";
        System.out.println("Table file path: " + filePath);

        Table table = TableReader.readTableFromFile(filePath);
        List<String> columnNames = Table.getColumnNames();

        if (valueList.size() != columnNames.size()) {
            return "[ERROR]: Number of values doesn't match number of columns.";
        }

        Row newRow = new Row();
        for (int i = 0; i < columnNames.size(); i++) {
            newRow.addData(columnNames.get(i), valueList.get(i));
            System.out.println("Adding data to new row: Column=" + columnNames.get(i) + ", Value=" + valueList.get(i));
        }

        if (table.getRows() == null) {
            table.setRows(new ArrayList<>());
        }

        // 获取下一个可用的id
        int nextId = table.getRows().size() + 1;
        newRow.addData("id", nextId);

        table.getRows().add(newRow);

        // 将新行追加到文件末尾
        appendRowToFile(newRow, filePath);

        return "[OK]\n" + readFileContent(filePath);
    }

    public static String readFileContent(String filePath) {
        StringBuilder content = new StringBuilder();
        try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
            String line;
            while ((line = reader.readLine()) != null) {
                content.append(line).append("\n");
            }
        } catch (IOException e) {
            System.err.println("[ERROR]: reading file: " + e.getMessage());
        }
        return content.toString();
    }
    // 将新行追加到文件末尾
    private static void appendRowToFile(Row newRow, String filePath) {
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(filePath, true))) {
            // 写入新行数据
            List<String> columnNames = new ArrayList<>(newRow.getRowData().keySet());
            List<Object> rowData = new ArrayList<>(newRow.getRowData().values());

            // 写入新行的每个数据值
            for (int i = 0; i < columnNames.size(); i++) {
                if (i > 0) {
                    writer.write("\t");
                }
                writer.write(rowData.get(i).toString());
            }
            writer.newLine();
        } catch (IOException e) {
            System.out.println("[ERROR]: appending row to file: " + e.getMessage());
        }
    }



    public String getTableName() {
        return tableName;
    }

    public void setTableName(String tableName) {
        this.tableName = tableName;
    }

    public static List<String> getColumnNames() {
        return columnNames;
    }

    public void setColumnNames(List<String> columnNames) {
        Table.columnNames = columnNames;
    }

    public List<Row> getRows() {
        return rows;
    }

    public void setRows(List<Row> rows) {
        this.rows = rows;
    }
}
